package com.leiduoduo.oms.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.auth0.jwt.JWT;
import com.leiduoduo.oms.annotation.PassToken;
import com.leiduoduo.oms.pojo.Dish;
import com.leiduoduo.oms.pojo.Order;
import com.leiduoduo.oms.pojo.OrderDish;
import com.leiduoduo.oms.pojo.Table;
import com.leiduoduo.oms.service.DishService;
import com.leiduoduo.oms.service.OrderDishService;
import com.leiduoduo.oms.service.OrderService;
import com.leiduoduo.oms.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Slf4j
@CrossOrigin
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    TableService tableService;
    @Autowired
    DishService dishService;
    @Autowired
    OrderDishService orderDishService;

    @PostMapping("/addOrder")
    @PassToken
    public boolean addOrder(Order order){
        return orderService.addOrder(order);
    }
    @PostMapping("/delOrder")
    @PassToken
    public boolean delOrder(Order order){
        return orderService.delOrder(order);
    }
    @GetMapping("/upOrder")
    @PassToken
    public boolean upOrder(Order order){
        return orderService.upOrder(order);
    }
    @GetMapping("/getOrderById")
    @PassToken
    public Order getOrderById(int id){
        return orderService.getOrderById(id);
    }
    @GetMapping("/getOrderList")
    @PassToken
    public List<Order> getOrderList(){
        return orderService.getOrderList();
    }
    @PostMapping("/createOrder")
    @PassToken
    public Map<String, Object> createOrder(HttpServletRequest request, @RequestBody JSONObject json){
        Map<String, Object> result = new HashMap<>();
        int tableId = json.getInteger("table_id");
        String dinnerCode = json.getString("dinner_code");
        List<Dish> dishes = json.parseObject(json.getJSONArray("dishes").toJSONString(),new TypeReference<List<Dish>>(){});
        //检查接收数据
        log.info(json.getJSONArray("dishes").toJSONString());
        log.info(dishes.toString());
        log.info("+++++++++++++++++++++++++++++++++createOrder++++++++++++++++++++++++++++++++++++++");
        String token = request.getHeader("authorization");
        String[] tokens =token.split(" ");
        token = tokens[1];
        String appCode = JWT.decode(token).getAudience().get(0);
        //通过tableId得到table，从而获得tableName
        Table table = tableService.getTableById(tableId);
        String tableName = table.getName();
        Order order = new Order();
        List<Integer> dishIds = new LinkedList<>();
        for (Dish dish : dishes ){
            dishIds.add(dish.getId());
        }
        log.info(dishIds.contains(0)+""+tableId+dinnerCode+"");
        if (dishIds.contains(0)||tableId==0||dinnerCode==null){
            result.put("error",406);
            result.put("msg","json格式错误");
        }else{
            //计算总价
            log.info(dishIds.toString());
            Map<String, Object> param = new HashMap<>();
            param.put("dishIds",dishIds);
            Double money = dishService.getMoneyByDish(dishIds);
            log.info(money.toString());
            String orderCode = System.currentTimeMillis()+""+dinnerCode;
            order.setTable_id(tableId)
                    .setDinner_code(dinnerCode)
                    .setUser_code(appCode)
                    .setTable_name(tableName)
                    .setMoney(money)
                    .setOrder_code(orderCode);
            boolean b = orderService.addOrder(order);
            for (Dish dish : dishes ) {
                OrderDish orderDish = new OrderDish();
                orderDish.setOrder_code(orderCode).setDish_id(dish.getId());
                orderDishService.addOrderDish(orderDish);
            }
            result.put("error",0);
            result.put("msg","success");
            result.put("data",order);
        }
        return result;
    }

    /**
     * 用户结账，订单状态改变
     * @param order_code 订单编码
     * @param pay_status 是否结账
     * @return
     */
    @PostMapping("/upOrderState")
    @PassToken
    public Map<String, Object> upOrderState(String order_code, boolean pay_status){
        Map<String, Object> result = new HashMap<>();
        if(null == order_code ){
            result.put("msg", "参数错误");
            result.put("errorcode",406);
        } else {
            if (pay_status){
                Order order = new Order();
                order.setOrder_code(order_code).setState(30);
                orderService.upOrderState(order);
                result.put("msg","支付成功");
                result.put("errorcode",0);
            } else {
                Order order = new Order();
                order.setOrder_code(order_code).setState(21);
                orderService.upOrderState(order);
                result.put("msg","支付失败");
                result.put("errorcode",0);
            }
        }
        return result;
    }
}
